﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace MVVMComun
{
   public  class BingService:ServiceModel
    {
       private string key = "KTiRp7wo3FRCmd/0kngr6H7Mik4lj5YLml9mzMafiTY";
       private String authParam ;
       private XNamespace Xns = XNamespace.Get("http://www.w3.org/2005/Atom");
       private XNamespace XnsM = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
       private XNamespace XnsD = XNamespace.Get("http://schemas.microsoft.com/ado/2007/08/dataservices");

       public event EventHandler<BingNewsResponseEventArgs> BingNewsServiceResponseReady;  

        private string size;

        public string Size
        {
            get { return size; }
            set { size = value; }
        }
         
       public BingService() {
           authParam = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("ignore" + ":" + key));
        }


        public async void  getNoticias(string query) {
            serviceUri = new Uri("https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27"+  query  + "%27&Market=%27es-ES%27&NewsSortBy=%27Date%27");
            HttpClient hc = new HttpClient();
            hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authParam);
            var result = await hc.GetStringAsync(serviceUri);
            XDocument doc = XDocument.Parse(result);

            List<Noticia> Entries = (from ent in doc.Elements().First().Descendants(Xns + "entry")
                          select new Noticia
                          {
                              Titulo = ent.Descendants(XnsD + "Title").First().Value,
                              Url = new Uri(ent.Descendants(XnsD + "Url").First().Value),
                              Fuente = ent.Descendants(XnsD + "Source").First().Value,
                              Descripcion = ent.Descendants(XnsD + "Description").First().Value,
                              Fecha = DateTime.Parse(ent.Descendants(XnsD + "Date").First().Value)
                          }).ToList() ;

            if (BingNewsServiceResponseReady != null)
                BingNewsServiceResponseReady(this, new BingNewsResponseEventArgs(Entries)); 
        
        }
    }
}
